package com.migraine.controller;

import com.alibaba.fastjson.JSONObject;
import com.migraine.model.Users;
import com.migraine.service.UsersService;
import com.migraine.websocket.WebSocketServer;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.migraine.service.impl.UsersServiceImpl;

import java.util.concurrent.Semaphore;

import java.util.Map;

@Controller
public class LoginController {
    @Autowired
    UsersService usersService;

    // 为下方注册流程定义资源包的总数为1 同一时刻只能有一个对数据库用户表的增加操作
    Semaphore semphore = new Semaphore(1);

    // 日志工具
    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);

    @RequestMapping("/")
    public String index() {
        return "forward:/views/homepage/home_page.html";
    }

    /**
     * 登录功能
     * @param map
     * @return
     */
    @ResponseBody
    @RequestMapping("/login")
    public String login(@RequestBody Map<String, String> map) {
        String username = map.get("username");
        String password = map.get("password");
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        JSONObject json = new JSONObject();
        try {
            // 登录成功
            subject.login(token);
            json.put("url", "/views/index.html");
            json.put("er", "0");
            //在服务器端保存用户的个人信息
            Session session = subject.getSession();
            String uid = usersService.getUsers(username).getUid();
            session.setAttribute("uid", uid);
            return json.toJSONString();
        } catch (UnknownAccountException e) {
            // 用户名不存在
            json.put("url", "/login.html");
            json.put("er", "1");
            return json.toJSONString();
        } catch (IncorrectCredentialsException e) {
            // 密码错误
            json.put("url", "/login.html");
            json.put("er", "2");
            return json.toJSONString();
        }

    }

    /**
     * 注册功能
     *
     * @param map
     * @return
     */
    @ResponseBody
    @RequestMapping("/regist")
    public String regist(@RequestBody Map<String, String> map) {
        String username = map.get("username");
        String password = map.get("password");

        boolean tmp = false;
        // 目前可用的资源量
        int availablePermits = semphore.availablePermits();
        // 有资源量时才能进行以下操作
        if (availablePermits > 0) {
            try {
                semphore.acquire(1);
                tmp = usersService.insertUsers(username, password);
                usersService.setPhoto(username, "https://tse4-mm.cn.bing.net/th/id/OIP-C.icmtPAEBY4b34eRiPY8SQgAAAA?w=187&h=186&c=7&r=0&o=5&dpr=1.25&pid=1.7");
            } catch (InterruptedException e) {
                logger.error("错误：",e);
                Thread.currentThread().interrupt();
            } finally {
                semphore.release(1);
            }
        } else {
            System.out.println("资源正被占用");
        }
        JSONObject json = new JSONObject();
        // 0状态代表成功注册
        if (tmp) {
            json.put("er", "0");
            return json.toJSONString();
        }

        // 1状态代表用户名重复
        json.put("er", "1");
        return json.toJSONString();
    }

}
